/**
 * 数据导出工具
 * 支持导出测试记录、统计数据等
 */

import { getTestHistory, getAllTestStats } from './testHistory.js'
import { getSettings } from './settingsManager.js'

/**
 * 导出所有数据
 * @returns {Object} 包含所有数据的对象
 */
export function exportAllData() {
	try {
		const exportData = {
			version: '1.0.0',
			exportTime: new Date().toISOString(),
			deviceInfo: getDeviceInfo(),
			testHistory: getAllTestHistory(),
			statistics: getAllTestStats(),
			settings: getSettings(),
			achievements: getAchievements()
		}
		
		return exportData
	} catch (error) {
		console.error('导出数据失败:', error)
		return null
	}
}

/**
 * 导出测试历史记录
 * @param {string} testType - 测试类型，不传则导出所有
 * @param {number} days - 导出最近多少天的数据，默认30天
 * @returns {Array} 测试记录数组
 */
export function exportTestHistory(testType = null, days = 30) {
	try {
		const cutoffDate = new Date()
		cutoffDate.setDate(cutoffDate.getDate() - days)
		
		if (testType) {
			const history = getTestHistory(testType)
			return history.filter(record => new Date(record.timestamp) >= cutoffDate)
		} else {
			const allHistory = []
			const testTypes = ['memory', 'reaction', 'chimp', 'visual', 'typing']
			
			testTypes.forEach(type => {
				const history = getTestHistory(type)
				const filteredHistory = history.filter(record => new Date(record.timestamp) >= cutoffDate)
				allHistory.push(...filteredHistory)
			})
			
			// 按时间排序
			return allHistory.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
		}
	} catch (error) {
		console.error('导出测试历史失败:', error)
		return []
	}
}

/**
 * 导出统计数据
 * @returns {Object} 统计数据对象
 */
export function exportStatistics() {
	try {
		return {
			overall: getAllTestStats(),
			detailed: getDetailedStats(),
			trends: getTrendData()
		}
	} catch (error) {
		console.error('导出统计数据失败:', error)
		return {}
	}
}

/**
 * 生成CSV格式的测试记录
 * @param {string} testType - 测试类型
 * @param {number} days - 导出天数
 * @returns {string} CSV格式字符串
 */
export function exportToCSV(testType = null, days = 30) {
	try {
		const history = exportTestHistory(testType, days)
		
		if (history.length === 0) {
			return ''
		}
		
		// CSV头部
		const headers = [
			'测试类型',
			'测试时间',
			'分数',
			'等级',
			'准确率',
			'反应时间',
			'难度',
			'持续时间',
			'备注'
		]
		
		let csvContent = headers.join(',') + '\n'
		
		// 数据行
		history.forEach(record => {
			const row = [
				record.testType || '',
				new Date(record.timestamp).toLocaleString('zh-CN'),
				record.score || '',
				record.level || '',
				record.accuracy ? `${(record.accuracy * 100).toFixed(1)}%` : '',
				record.reactionTime ? `${record.reactionTime}ms` : '',
				record.difficulty || '',
				record.duration ? `${record.duration}s` : '',
				record.notes || ''
			]
			
			// 处理包含逗号的字段
			const escapedRow = row.map(field => {
				const str = String(field)
				if (str.includes(',') || str.includes('"') || str.includes('\n')) {
					return `"${str.replace(/"/g, '""')}"`
				}
				return str
			})
			
			csvContent += escapedRow.join(',') + '\n'
		})
		
		return csvContent
	} catch (error) {
		console.error('生成CSV失败:', error)
		return ''
	}
}

/**
 * 生成JSON格式的导出数据
 * @param {Object} data - 要导出的数据
 * @returns {string} JSON格式字符串
 */
export function exportToJSON(data) {
	try {
		return JSON.stringify(data, null, 2)
	} catch (error) {
		console.error('生成JSON失败:', error)
		return ''
	}
}

/**
 * 保存数据到文件
 * @param {string} content - 文件内容
 * @param {string} filename - 文件名
 * @param {string} type - 文件类型 (json/csv)
 */
export function saveToFile(content, filename, type = 'json') {
	try {
		// 在小程序环境中，通常需要调用特定的API来保存文件
		// 这里提供一个通用的实现
		
		const timestamp = new Date().toISOString().slice(0, 19).replace(/:/g, '-')
		const fullFilename = `${filename}_${timestamp}.${type}`
		
		// 尝试使用uni-app的文件系统API
		if (typeof uni !== 'undefined') {
			// 获取文件系统管理器
			const fs = uni.getFileSystemManager()
			const filePath = `${uni.env.USER_DATA_PATH}/${fullFilename}`
			
			fs.writeFile({
				filePath: filePath,
				data: content,
				encoding: 'utf8',
				success: () => {
					uni.showToast({
						title: '导出成功',
						icon: 'success'
					})
					
					// 可以进一步处理，比如分享文件
					shareFile(filePath, fullFilename)
				},
				fail: (error) => {
					console.error('保存文件失败:', error)
					uni.showToast({
						title: '导出失败',
						icon: 'error'
					})
				}
			})
		} else {
			// 浏览器环境下载文件
			const blob = new Blob([content], { type: `text/${type}` })
			const url = URL.createObjectURL(blob)
			const a = document.createElement('a')
			a.href = url
			a.download = fullFilename
			a.click()
			URL.revokeObjectURL(url)
		}
	} catch (error) {
		console.error('保存文件失败:', error)
	}
}

/**
 * 分享文件
 * @param {string} filePath - 文件路径
 * @param {string} filename - 文件名
 */
function shareFile(filePath, filename) {
	try {
		if (typeof uni !== 'undefined') {
			uni.shareWithSystem({
				type: 'file',
				filePath: filePath,
				success: () => {
					console.log('分享成功')
				},
				fail: (error) => {
					console.log('分享失败:', error)
					// 如果分享失败，可以提示用户文件保存位置
					uni.showModal({
						title: '文件已保存',
						content: `文件已保存到：${filePath}`,
						showCancel: false
					})
				}
			})
		}
	} catch (error) {
		console.error('分享文件失败:', error)
	}
}

/**
 * 获取设备信息
 * @returns {Object} 设备信息
 */
function getDeviceInfo() {
	try {
		if (typeof uni !== 'undefined') {
			const systemInfo = uni.getSystemInfoSync()
			return {
				platform: systemInfo.platform,
				system: systemInfo.system,
				version: systemInfo.version,
				model: systemInfo.model,
				screenWidth: systemInfo.screenWidth,
				screenHeight: systemInfo.screenHeight
			}
		} else {
			return {
				platform: 'web',
				userAgent: navigator.userAgent,
				screenWidth: screen.width,
				screenHeight: screen.height
			}
		}
	} catch (error) {
		console.error('获取设备信息失败:', error)
		return {}
	}
}

/**
 * 获取所有测试历史记录
 * @returns {Object} 按测试类型分组的历史记录
 */
function getAllTestHistory() {
	try {
		const testTypes = ['memory', 'reaction', 'chimp', 'visual', 'typing']
		const allHistory = {}
		
		testTypes.forEach(type => {
			allHistory[type] = getTestHistory(type)
		})
		
		return allHistory
	} catch (error) {
		console.error('获取测试历史失败:', error)
		return {}
	}
}

/**
 * 获取成就数据
 * @returns {Array} 成就列表
 */
function getAchievements() {
	try {
		const achievements = uni.getStorageSync('achievements') || []
		return achievements
	} catch (error) {
		console.error('获取成就数据失败:', error)
		return []
	}
}

/**
 * 获取详细统计数据
 * @returns {Object} 详细统计
 */
function getDetailedStats() {
	try {
		const testTypes = ['memory', 'reaction', 'chimp', 'visual', 'typing']
		const detailedStats = {}
		
		testTypes.forEach(type => {
			const history = getTestHistory(type)
			if (history.length > 0) {
				detailedStats[type] = {
					totalTests: history.length,
					bestScore: Math.max(...history.map(h => h.score || 0)),
					averageScore: history.reduce((sum, h) => sum + (h.score || 0), 0) / history.length,
					lastTest: history[0],
					firstTest: history[history.length - 1],
					scoreDistribution: getScoreDistribution(history),
					difficultyStats: getDifficultyStats(history)
				}
			}
		})
		
		return detailedStats
	} catch (error) {
		console.error('获取详细统计失败:', error)
		return {}
	}
}

/**
 * 获取趋势数据
 * @returns {Object} 趋势数据
 */
function getTrendData() {
	try {
		const testTypes = ['memory', 'reaction', 'chimp', 'visual', 'typing']
		const trendData = {}
		
		testTypes.forEach(type => {
			const history = getTestHistory(type)
			if (history.length > 0) {
				trendData[type] = {
					daily: getDailyTrend(history),
					weekly: getWeeklyTrend(history),
					monthly: getMonthlyTrend(history)
				}
			}
		})
		
		return trendData
	} catch (error) {
		console.error('获取趋势数据失败:', error)
		return {}
	}
}

/**
 * 获取分数分布
 * @param {Array} history - 历史记录
 * @returns {Object} 分数分布
 */
function getScoreDistribution(history) {
	const distribution = {
		'0-20': 0,
		'21-40': 0,
		'41-60': 0,
		'61-80': 0,
		'81-100': 0
	}
	
	history.forEach(record => {
		const score = record.score || 0
		if (score <= 20) distribution['0-20']++
		else if (score <= 40) distribution['21-40']++
		else if (score <= 60) distribution['41-60']++
		else if (score <= 80) distribution['61-80']++
		else distribution['81-100']++
	})
	
	return distribution
}

/**
 * 获取难度统计
 * @param {Array} history - 历史记录
 * @returns {Object} 难度统计
 */
function getDifficultyStats(history) {
	const stats = {}
	
	history.forEach(record => {
		const difficulty = record.difficulty || 'unknown'
		if (!stats[difficulty]) {
			stats[difficulty] = {
				count: 0,
				totalScore: 0,
				bestScore: 0
			}
		}
		
		stats[difficulty].count++
		stats[difficulty].totalScore += record.score || 0
		stats[difficulty].bestScore = Math.max(stats[difficulty].bestScore, record.score || 0)
	})
	
	// 计算平均分
	Object.keys(stats).forEach(difficulty => {
		stats[difficulty].averageScore = stats[difficulty].totalScore / stats[difficulty].count
	})
	
	return stats
}

/**
 * 获取每日趋势
 * @param {Array} history - 历史记录
 * @returns {Array} 每日数据
 */
function getDailyTrend(history) {
	const dailyData = {}
	
	history.forEach(record => {
		const date = new Date(record.timestamp).toDateString()
		if (!dailyData[date]) {
			dailyData[date] = {
				date,
				count: 0,
				totalScore: 0,
				bestScore: 0
			}
		}
		
		dailyData[date].count++
		dailyData[date].totalScore += record.score || 0
		dailyData[date].bestScore = Math.max(dailyData[date].bestScore, record.score || 0)
	})
	
	// 转换为数组并计算平均分
	return Object.values(dailyData).map(day => ({
		...day,
		averageScore: day.totalScore / day.count
	})).sort((a, b) => new Date(a.date) - new Date(b.date))
}

/**
 * 获取每周趋势
 * @param {Array} history - 历史记录
 * @returns {Array} 每周数据
 */
function getWeeklyTrend(history) {
	const weeklyData = {}
	
	history.forEach(record => {
		const date = new Date(record.timestamp)
		const weekStart = new Date(date)
		weekStart.setDate(date.getDate() - date.getDay())
		const weekKey = weekStart.toDateString()
		
		if (!weeklyData[weekKey]) {
			weeklyData[weekKey] = {
				week: weekKey,
				count: 0,
				totalScore: 0,
				bestScore: 0
			}
		}
		
		weeklyData[weekKey].count++
		weeklyData[weekKey].totalScore += record.score || 0
		weeklyData[weekKey].bestScore = Math.max(weeklyData[weekKey].bestScore, record.score || 0)
	})
	
	return Object.values(weeklyData).map(week => ({
		...week,
		averageScore: week.totalScore / week.count
	})).sort((a, b) => new Date(a.week) - new Date(b.week))
}

/**
 * 获取每月趋势
 * @param {Array} history - 历史记录
 * @returns {Array} 每月数据
 */
function getMonthlyTrend(history) {
	const monthlyData = {}
	
	history.forEach(record => {
		const date = new Date(record.timestamp)
		const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
		
		if (!monthlyData[monthKey]) {
			monthlyData[monthKey] = {
				month: monthKey,
				count: 0,
				totalScore: 0,
				bestScore: 0
			}
		}
		
		monthlyData[monthKey].count++
		monthlyData[monthKey].totalScore += record.score || 0
		monthlyData[monthKey].bestScore = Math.max(monthlyData[monthKey].bestScore, record.score || 0)
	})
	
	return Object.values(monthlyData).map(month => ({
		...month,
		averageScore: month.totalScore / month.count
	})).sort((a, b) => a.month.localeCompare(b.month))
}

/**
 * 导入数据
 * @param {Object} importData - 要导入的数据
 * @returns {boolean} 导入是否成功
 */
export function importData(importData) {
	try {
		if (!importData || typeof importData !== 'object') {
			throw new Error('无效的导入数据')
		}
		
		// 验证数据格式
		if (!importData.version || !importData.exportTime) {
			throw new Error('数据格式不正确')
		}
		
		// 备份当前数据
		const backupData = exportAllData()
		uni.setStorageSync('dataBackup', backupData)
		
		// 导入测试历史
		if (importData.testHistory) {
			Object.keys(importData.testHistory).forEach(testType => {
				uni.setStorageSync(`testHistory_${testType}`, importData.testHistory[testType])
			})
		}
		
		// 导入设置
		if (importData.settings) {
			uni.setStorageSync('userSettings', importData.settings)
		}
		
		// 导入成就
		if (importData.achievements) {
			uni.setStorageSync('achievements', importData.achievements)
		}
		
		return true
	} catch (error) {
		console.error('导入数据失败:', error)
		return false
	}
}

/**
 * 恢复备份数据
 * @returns {boolean} 恢复是否成功
 */
export function restoreBackup() {
	try {
		const backupData = uni.getStorageSync('dataBackup')
		if (!backupData) {
			throw new Error('没有找到备份数据')
		}
		
		return importData(backupData)
	} catch (error) {
		console.error('恢复备份失败:', error)
		return false
	}
}